package nrpc.server;

import java.io.IOException;
import java.net.InetSocketAddress;

import nrpc.client.ClientStub;
import nrpc.client.reqst.SingleRequestStrategy;
import nrpc.client.serst.ConfiguredServiceStrategy;
import nrpc.client.skst.SingleSocketStrategy;
import nrpc.client.slst.SingleSelectStrategy;
import nrpc.impl.RegisterHandler;
import nrpc.message.meta.ServerEntry;

public class ServerRegisterStub extends ServerStub {

	// 心跳间隔
	private final static long INTERVAL = 10000;
	
	private ClientStub stub;
	private RegisterHandler handler;
	private String url;
	private long id;
	private volatile boolean alive = true;
	
	public ServerRegisterStub(int port, String url, InetSocketAddress registerAddress) {
		super(port);
		try {
			stub = new ClientStub(
				new SingleRequestStrategy(
					new SingleSelectStrategy(
							new ConfiguredServiceStrategy(registerAddress)),
					new SingleSocketStrategy()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.url = url;
		this.handler = stub.getProxyInstance(RegisterHandler.class);
	} 	
	
	@Override
	public void registerInstance(Object obj, Class<?> interfaceClass) throws IOException {
		super.registerInstance(obj, interfaceClass);
		this.id = handler.register(url, new ServerEntry(getLocalAddress()));
		new Thread(){
			public void run() {
				while(alive){
					try {
						Thread.sleep(INTERVAL);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (ServerRegisterStub.this) {
						if(alive)handler.pulse(url, id);
					}
				}
			};
		}.start();
	}
	
	@Override
	public synchronized void close() {
		alive = false;
		handler.cancelService(url, id);
		stub.close();
		super.close();
	}
	
}
